package com.jwthhealth_pub.wristband.steps.fragment;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.jwthhealth_pub.R;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.utils.TimeUtil;
import com.jwthhealth_pub.wristband.newbloodpressure.utils.MyAxisValueFormatter;
import com.jwthhealth_pub.wristband.newbloodpressure.utils.XYMarkerView;
import com.jwthhealth_pub.wristband.steps.adapter.MyStepsViewPagerAdapter;
import com.jwthhealth_pub.wristband.steps.bean.StepsYearBean;
import com.jwthhealth_pub.wristband.steps.utils.MyValueFormatter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FragmentYear extends Fragment implements
        OnChartValueSelectedListener ,ViewPager.OnPageChangeListener{
    @BindView(R.id.customBarChart)
    LinearLayout customBarChart;
    @BindView(R.id.tv_typeDate)
    TextView tv_typeDate;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.btn_left)
    Button btn_left;
    @BindView(R.id.btn_right)
    Button btn_right;
    @BindView(R.id.tv_ka_stpes)
    TextView tv_ka_stpes;
    @BindView(R.id.tv_sum_stpes)
    TextView tv_sum_stpes;
    @BindView(R.id.tv_km_stpes)
    TextView tv_km_stpes;
    @BindView(R.id.tv_avg_stpes)
    TextView tv_avg_stpes;


    BarChart barChart;

    List<StepsYearBean.DataBean> yearList = new ArrayList<>();
    int count =0;
    private int postion = 0;
    private int sumData;  //表示的总数
    int pon ;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_year, container, false);
        ButterKnife.bind(this, view);
        initData();
        return view;

    }
    private void initData() {
        String uid= "";
        String token= "";
        LoginModel.DataBean userinfoModel = Contas.getObject(getActivity(), LoginModel.DataBean.class);
        if(userinfoModel!=null){
            uid = userinfoModel.getId();
            token= userinfoModel.getAndroidtoken();
        }
        String mDate = TimeUtil.getNowDateShort();
        Call<StepsYearBean> stepsDayBean = ApiHelper.getwalkLogYear(uid,mDate,token);
        stepsDayBean.enqueue(new Callback<StepsYearBean>() {
            @Override
            public void onResponse(Call<StepsYearBean> call, Response<StepsYearBean> response) {
                StepsYearBean body = response.body();
                if (body == null) return;
                if (body.getCode().equals("0")){
                    yearList=  body.getData();
                    Collections.reverse(yearList); // 倒序排列  年的不需要倒序
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initView();
                        }
                    });
                }else{
                }
            }

            @Override
            public void onFailure(Call<StepsYearBean> call, Throwable t) {

                Log.i("tag",t.getMessage());
            }
        });

    }
    private void initView() {

        List<View> view = new ArrayList<>();
        LayoutInflater lf = getLayoutInflater().from(getActivity());

        if(!yearList.isEmpty()){
            for (int i = 0; i<yearList.size();i++){
                View viewDay = lf.inflate(R.layout.item_barchart, null);
                barChart = viewDay.findViewById(R.id.barChart);
                view.add(viewDay);
                StepsYearBean.DataBean model = yearList.get(i);
                initBarDatas(model,i);

            }
            sumData = yearList.size();
            pon = sumData;

            tv_typeDate.setText(yearList.get(yearList.size()-1).getName());
//      //下面是四个
            tv_sum_stpes.setText(yearList.get(yearList.size()-1).getTotla_step());
            tv_ka_stpes.setText(yearList.get(yearList.size()-1).getTotal_calorie());
            tv_km_stpes.setText(yearList.get(yearList.size()-1).getTotal_odo());
            tv_avg_stpes.setText(yearList.get(yearList.size()-1).getAvg_step());


        }
        MyStepsViewPagerAdapter adapter =new  MyStepsViewPagerAdapter(view);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(sumData);
        viewPager.setOnPageChangeListener(this);
    }

    @OnClick({R.id.btn_left,R.id.btn_right})
    //左右点击选择
    public void checkClick(View v){
        pon = viewPager.getCurrentItem();
        if(v.getId()==R.id.btn_left){
            pon = pon-1;
            if(pon<0){
                return;
            }
            postion = postion-1;
            viewPager.setCurrentItem(pon);

            tv_typeDate.setText(yearList.get(pon).getName());
            tv_sum_stpes.setText(yearList.get(pon).getTotla_step());
            tv_ka_stpes.setText(yearList.get(pon).getTotal_calorie());
            tv_km_stpes.setText(yearList.get(pon).getTotal_odo());
            tv_avg_stpes.setText(yearList.get(pon).getAvg_step());
        }
        if(v.getId()==R.id.btn_right){
            pon = pon+1;
            if(pon>yearList.size()-1){
                return;
            }
            postion = postion+1;
            viewPager.setCurrentItem(pon);
            tv_typeDate.setText(yearList.get(pon).getName());
            tv_sum_stpes.setText(yearList.get(pon).getTotla_step());
            tv_ka_stpes.setText(yearList.get(pon).getTotal_calorie());
            tv_km_stpes.setText(yearList.get(pon).getTotal_odo());
            tv_avg_stpes.setText(yearList.get(pon).getAvg_step());

        }

    }
    private void initBarDatas(StepsYearBean.DataBean  listBeanX,int poi) {
        barChart.setOnChartValueSelectedListener(this);
        barChart.animateY(1000, Easing.EasingOption.Linear);
        barChart.animateX(1000, Easing.EasingOption.Linear);
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);

        barChart.getDescription().setEnabled(false);
        barChart.setMaxVisibleValueCount(300);

        // scaling can now only be done on x- and y-axis separately
        barChart.setPinchZoom(false);

        barChart.setDrawGridBackground(false);//是否显示网格



        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        IAxisValueFormatter xAxisFormatter = new YearFormatter(poi);
        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.setTextSize(10.5f);


        IAxisValueFormatter custom = new MyAxisValueFormatter();

        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setDrawGridLines(false);//是否画线
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setEnabled(false);

        YAxis rightAxis = barChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setDrawGridLines(false);//是否画线
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        rightAxis.setEnabled(false);

        barChart.getLegend().setEnabled(false);

        XYMarkerView mv = new XYMarkerView(getActivity(), xAxisFormatter);
        mv.setChartView(barChart); // For bounds control
//        barChart.setMarker(mv); // Set the marker to the chart
        barChart.setBorderWidth(50f);

        setBarChartData(listBeanX,poi);
    }

    private void setBarChartData(StepsYearBean.DataBean  listBeanX,int poi) {

        List<StepsYearBean.DataBean.ListBean> mtempList= listBeanX.getList();
//        Collections.reverse(mtempList); // 倒序排列
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 1;i<=mtempList.size();i++){

            BarEntry barEntry =    new BarEntry(i-1,Float.valueOf(listBeanX.getList().get(i-1).getTotla_step()));
            yVals1.add(barEntry);
        }


        BarDataSet set1;  //这就是每个柱状图的实例
        if (barChart.getData() != null &&
                barChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "步数");
            set1.setDrawIcons(false);

            int[] PASTEL_COLORS = {  //设置每个柱状图背景色
                    Color.rgb(75, 204, 209)
            };
            set1.setColors(PASTEL_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);//调节顶部字体大小
            data.setValueTextColor(R.color.mainMotion_li);
            MyValueFormatter custom = new MyValueFormatter();
            data.setValueFormatter(custom);
            data.setBarWidth(0.15f); //调节间距的
            Float valueF = data.getYMax();
            data.setValueFormatter(new myValueFormatter(valueF));
            barChart.setData(data);
        }
    }
    protected RectF mOnValueSelectedRectF = new RectF();
    @SuppressLint("NewApi")
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        RectF bounds = mOnValueSelectedRectF;
        barChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = barChart.getPosition(e, YAxis.AxisDependency.LEFT);

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() { }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    //页面滑动后调用
    @Override
    public void onPageSelected(int p) {

        pon = viewPager.getCurrentItem();
        tv_typeDate.setText(yearList.get(pon).getName());
        tv_sum_stpes.setText(yearList.get(pon).getTotla_step());
        tv_ka_stpes.setText(yearList.get(pon).getTotal_calorie());
        tv_km_stpes.setText(yearList.get(pon).getTotal_odo());
        tv_avg_stpes.setText(yearList.get(pon).getAvg_step());
    }
    @Override
    public void onPageScrollStateChanged(int state) {
    }

    //这是设置下端的数值
    class YearFormatter implements IAxisValueFormatter
    {

        private int pon;
        public YearFormatter(int pon) {
            this.pon = pon;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String appendix="";
            if(value==0.0) {
                appendix = "1";
            }else if(value==1.0){
                appendix = "2";
            }else if(value==2.0){
                appendix = "3";
            }else if(value==3.0){
                appendix = "4";
            }else if(value==4.0){
                appendix = "5";
            }else if(value==5.0){
                appendix = "6";
            }else if(value==6.0){
                appendix = "7";
            }else if(value==7.0){
                appendix = "8";
            }else if(value==8.0){
                appendix = "9";
            }else if(value==9.0){
                appendix = "10";
            }else if(value==10.0){
                appendix = "11";
            }else if(value==11.0){
                appendix = "12";
            }else{
                appendix = "";
            }

            return appendix;
        }

    }


    //这是设置上端的显示的最大数值
    class myValueFormatter implements IValueFormatter
    {
        boolean isRest;
        private Float valueF;
        private Float valueX;
        public myValueFormatter(Float valueF){
            this.valueF = valueF;
        }

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            if(!isRest){
                if(valueF==value&&value!=0){
                    valueX= entry.getX();
                    isRest=true;
                    DecimalFormat decimalFormat=new DecimalFormat("#");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String str =decimalFormat.format(valueF);//format 返回的是字符串
                    return str;
                }else{
                    return "";
                }
            }else{
                if(valueX==entry.getX()){
                    DecimalFormat decimalFormat=new DecimalFormat("#");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String str =decimalFormat.format(valueF);//format 返回的是字符串
                    return str;
                }else{
                    return "";
                }

            }
        }
    }


}
